<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : UserRecharge.php
 * Created on : 2023-4-5 20:59:05
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace app\models;

use think\Model;

/**
 * 
 * Class UserRecharge
 * Tiger <1192851302@qq.com> 2023-4-5 20:59:05
 */
class UserRecharge extends Model {

    /**
     * 获取数据列表-分页
     * @author Tiger <1192851302@qq.com>
     * @param array $where
     * @return array
     */
    public static function getList($where) {
        $model = self::alias('a')
                ->join('user u ', 'u.id= a.user_id');
        if (!empty($where['search'])) {
            $model->where('u.nickname|u.mobile', 'LIKE', '%' . $where['search'] . '%');
        }
        if (!empty($where['date'])) {
            [$start_date, $end_date] = explode(' - ', $where['date']);
            $start_date && $end_date ? $model->whereBetweenTime('a.time', $start_date, $end_date . ' 23:59:59') : '';
        }
        if (!empty($where['status'])) {
            $model->where('a.status', $where['status']);
        }
        $models = $model->order('a.time desc')->field(['a.*', 'u.nickname', 'u.mobile'])
                ->paginate(input('limit', 10));
        return [
            'code' => 0,
            'items' => $models->items(),
            'total' => $models->total()
        ];
    }

    /**
     * 在线支付成功
     * @author Tiger <1192851302@qq.com>
     * @param type $message 微信回调数据
     * @param type $payment {id,join_id} 系统支付表数据
     * @return boolean
     */
    public static function paySuccess($message, $payment) {
        //支付通知成功
        \app\models\Payment::update(['callback_status' => 1], ['id' => $payment['id']]);
        $order_id = $payment['join_id'];

        $order = self::where('id', $order_id)->where('status', 0)->find();
        if (empty($order)) {
            return true;
        }
        //更新订单表状态为1
        self::update(['status' => 1], ['id' => $order_id]);
        $number = bcadd($order->buy_nomey, $order->give_nomey, 2);
        //更新用户
        $user = \app\models\User::where('id', $order->user_id)->field(['id', 'money'])->find();
        $user->money = bcadd($order->buy_nomey, $user->money, 2);
        $user->giveMoney = bcadd($order->give_nomey, $user->giveMoney, 2);
        $user->save();
        //写入账单
        \app\models\UserBill::income($order->user_id, $order_id, '在线充值', 'money', 'recharge', $number, bcadd($user->money_balance, $number, 2), 1);
        return true;
    }

}
